﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Xts
{
    namespace IceRuntime
    {
        public class XStormSubscriber : XStormBase
        {
            protected Ice.ObjectAdapter x_objAdapter;

            public XStormSubscriber(ref Ice.Communicator ic, ref Ice.Logger logger, ref Ice.ObjectAdapter objAdapter)
                :base(ref ic, ref logger)
            {
                x_objAdapter = objAdapter;
            }

            public bool SubscribeTopic(string topicName, Ice.Object subServant, out Ice.ObjectPrx subscriberPrx)
            {
                subscriberPrx = null;
                if (x_ic.isShutdown() || x_objAdapter.isDeactivated())
                {
                    x_logger.error("Ice runtime is not valid. Can't subscribe topic.");
                    return false;
                }

                IceStorm.TopicPrx topicPrx = RetrieveTopic(topicName);
                if (topicPrx == null)
                {
                    x_logger.error(topicName + ": failed to get topic proxy.");
                    return false;
                }

                try
                {
                    subscriberPrx = x_objAdapter.addWithUUID(subServant);
                    topicPrx.subscribeAndGetPublisher(x_qos, subscriberPrx);
                    return true;
                }
                catch(IceStorm.AlreadySubscribed)
                {
                    x_logger.error(topicName + ": Already Subscribed.");
                }
                catch (Ice.Exception ex)
                {
                    x_logger.error(ex.Message);
                }

                return false;
            }

            public bool UnSubscribeTopic(string topicName, ref Ice.ObjectPrx subscriberPrx)
            {
                IceStorm.TopicPrx topicPrx = RetrieveTopic(topicName);
                if (topicPrx == null)
                {
                    x_logger.error(topicName + ": failed to get topic proxy.");
                    return false;
                }

                try
                {
                    topicPrx.unsubscribe(subscriberPrx);
                    x_objAdapter.remove(subscriberPrx.ice_getIdentity());
                    return true;
                }
                catch (IceStorm.NoSuchTopic)
                {
                    x_logger.error(topicName + " is not exist. Can't unsubscribe.");
                }
                catch (Ice.Exception ex)
                {
                    x_logger.error(ex.Message);
                }

                return false;
            }
        }
    }
}
